import React, { useEffect } from "react";
import "./App.less";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import {
  NavBar,
  Empty,
  SwipeCell,
  ProductCard,
  Button,
  Checkbox,
} from "react-vant";
const App = () => {
  const car = useSelector((state) => state.car);
  const flag = car.length === 0;
  const dispatch = useDispatch();
  const totalPrice = car.reduce((p, n) => n.state ?   p + n.count * n.price : p, 0);
  const fetchList = async () => {
    const resp = await axios.get("/api/car");
    dispatch({ type: "setCar", payload: resp.data.data });
  };
  useEffect(() => {
    fetchList();
  }, []);
  return (
    <div>
      <NavBar
        title="购物车"
        leftArrow=""
        rightText="清空"
        onClickRight={() => dispatch({ type: "clearCar" })}
      ></NavBar>
      {flag ? (
        <Empty image="error" description="购物车空空如也～～" />
      ) : (
        <div>
          {car.map((v, i) => {
            return (
              <SwipeCell
                key={i}
                rightAction={
                  <Button
                    onClick={() => dispatch({ type: "delCar", payload: v })}
                    style={{ height: "100%" }}
                    square
                    type="danger"
                  >
                    删除
                  </Button>
                }
              >
                <div style={{ display: "flex" }}>
                  <div style={{ flexShrink: 0, paddingTop: 10 }}>
                    <Checkbox
                      checked={v.state}
                      onChange={() =>
                        dispatch({ type: "changeState", payload: v })
                      }
                    ></Checkbox>
                  </div>
                  <div style={{ flex: 1 }}>
                    <ProductCard
                      num={v.count}
                      price={v.price}
                      desc={v.desc}
                      title={v.title}
                      thumb={v.image}
                      priceTop={
                        <div>{"小记：" + (v.price * v.count).toFixed(2)}</div>
                      }
                    />
                  </div>
                </div>
              </SwipeCell>
            );
          })}
        </div>
      )}
      <div>{totalPrice.toFixed(2)}</div>
    </div>
  );
};

export default App;
